package com.wsz.logistic.common.interceptor;

import com.wsz.logistic.common.annotation.CreatTime;
import com.wsz.logistic.common.annotation.CreatUser;
import com.wsz.logistic.common.annotation.UpdateTime;
import com.wsz.logistic.common.annotation.UpdateUser;
import com.wsz.logistic.common.util.SessionInfo;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @Author PangJunjie
 * @Date 2024/2/1/001
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class CreateOrUpdateInterceptor extends SessionInfo implements Interceptor {
    public Object intercept(Invocation invocation) throws Throwable {
        /*获取SQL执行器*/
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        /*获取被执行的SQL语句对象*/
        SqlCommandType commandType = statement.getSqlCommandType();
        /*获取执行添加或修改时传递的实体类对象*/
        Object parameter = invocation.getArgs()[1];
        /*通过反射获取实体类的属性对象*/
        Field[] fields = parameter.getClass().getDeclaredFields();//获取所有属性
        /*遍历所有属性*/
        for (Field f : fields) {
            /*开启数据注入的支持*/
            f.setAccessible(true);

            Integer loginId;
            /*if (getAdminId() != null) {
                loginId = getAdminId();
            } else if (getVipId() != null) {
                loginId = getVipId();*/
            if (getLoginId() != null) {
                loginId = getLoginId();
            } else {
                loginId = 1;
            }


            /*判断属性是否有指定的注解*/
            if (f.getAnnotation(CreatTime.class) != null) {
                /*判断SQL行为是否为添加*/
                if (commandType.equals(SqlCommandType.INSERT)) {
                    /*填入数据*/
                    f.set(parameter, new Date());
                }
            } else if (f.getAnnotation(CreatUser.class) != null) {
                if (commandType.equals(SqlCommandType.INSERT)) {
                    f.set(parameter, loginId);
                }
            } else if (f.getAnnotation(UpdateTime.class) != null) {
                if (commandType.equals(SqlCommandType.UPDATE)) {
                    f.set(parameter, new Date());
                }
            } else if (f.getAnnotation(UpdateUser.class) != null) {
                if (commandType.equals(SqlCommandType.UPDATE)) {
                    f.set(parameter, loginId);
                }
            }
        }
        return invocation.proceed();//放行
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
}
